local function onburnt(inst)
    inst.burnt = true
    inst.components.unwrappable:Unwrap()
end

local function onignite(inst)
    inst.components.unwrappable.canbeunwrapped = false
end

local function onextinguish(inst)
    inst.components.unwrappable.canbeunwrapped = true
end

local function MakeBundle(name, loot, tossloot, setupdata)
    local assets =
    {
        Asset("ANIM", "anim/" .. name .. ".zip"),
    }

    local prefabs =
    {
        "ash",
    }

    if loot ~= nil then
        for _, v in ipairs(loot) do
            table.insert(prefabs, v)
        end
    end

    local function OnWrapped(inst)
        inst.AnimState:PlayAnimation("idle")
    end

    local function OnUnwrapped(inst, pos, doer)
        if inst.burnt then
            SpawnPrefab("ash").Transform:SetPosition(pos:Get())
        else
            local loottable = setupdata.lootfn(inst, doer) or loot
            if loottable ~= nil then
                local moisture = inst.components.inventoryitem:GetMoisture()
                local iswet = inst.components.inventoryitem:IsWet()
                local cookbookupdater = doer.components.cookbookupdater
                for i, v in ipairs(loottable) do
                    local item = SpawnPrefab(v)
                    if item ~= nil then
                        if item.Physics ~= nil then
                            item.Physics:Teleport(pos:Get())
                        else
                            item.Transform:SetPosition(pos:Get())
                        end
                        if item.components.inventoryitem ~= nil then
                            item.components.inventoryitem:InheritMoisture(moisture, iswet)
                            if tossloot then
                                item.components.inventoryitem:OnDropped(true, .5)
                            end
                        end
                        --在食谱书中解锁
                        if cookbookupdater ~= nil and v ~= "tf_rainbow_apple" then
                            cookbookupdater:LearnRecipe(v, { "tf_box", "tf_box", "tf_box", "tf_box" })
                        end
                    end
                end
            end
        end
        if doer ~= nil and doer.SoundEmitter ~= nil then
            doer.SoundEmitter:PlaySound("dontstarve/common/together/packaged")
        end
        inst.components.finiteuses:Use(1)
    end

    local function fn()
        local inst = CreateEntity()

        inst.entity:AddTransform()
        inst.entity:AddAnimState()
        inst.entity:AddNetwork()

        MakeInventoryPhysics(inst)

        inst.AnimState:SetBank(name)
        inst.AnimState:SetBuild(name)
        inst.AnimState:PlayAnimation("idle")

        inst:AddTag("bundle")

        --unwrappable (from unwrappable component) added to pristine state for optimization
        inst:AddTag("unwrappable")

        inst.entity:SetPristine()

        if not TheWorld.ismastersim then
            return inst
        end

        inst:AddComponent("inspectable")

        inst:AddComponent("inventoryitem")
        inst.components.inventoryitem:SetSinks(true)

        inst:AddComponent("unwrappable")
        inst.components.unwrappable:SetOnWrappedFn(OnWrapped)
        inst.components.unwrappable:SetOnUnwrappedFn(OnUnwrapped)

        inst:AddComponent("finiteuses")
        inst.components.finiteuses:SetMaxUses(3)
        inst.components.finiteuses:SetUses(3)
        inst.components.finiteuses:SetOnFinished(inst.Remove)

        MakeSmallBurnable(inst, TUNING.SMALL_BURNTIME)
        MakeSmallPropagator(inst)
        inst.components.propagator.flashpoint = 10 + math.random() * 5
        inst.components.burnable:SetOnBurntFn(onburnt)
        inst.components.burnable:SetOnIgniteFn(onignite)
        inst.components.burnable:SetOnExtinguishFn(onextinguish)

        MakeHauntableLaunchAndIgnite(inst)

        if setupdata ~= nil and setupdata.master_postinit ~= nil then
            setupdata.master_postinit(inst, setupdata)
        end

        return inst
    end

    return Prefab(name, fn, assets, prefabs)
end

local tf_box =
{
    loottable =
    {
        tf_hamburger = 0,
        tf_rice_ball = 0,
        tf_sandwich = 0,
    },

    UpdateLootFood = function(loottable, doer)
        if doer and doer.components.tf_apple and doer.components.tf_apple.has_opened == false then
            loottable["tf_hamburger"] = 0
            loottable["tf_rice_ball"] = 0
            loottable["tf_sandwich"] = 0
            loottable["tf_rainbow_apple"] = 1
            doer.components.tf_apple.has_opened = true
            return
        end
        local health = doer ~= nil and doer.components.health or nil
        local sanity = doer ~= nil and doer.components.sanity or nil
        local hunger = doer ~= nil and doer.components.hunger or nil
        if not health or not sanity or not hunger then
            loottable["tf_hamburger"] = 98
            loottable["tf_rice_ball"] = 98
            loottable["tf_sandwich"] = 98
            loottable["tf_rainbow_apple"] = 6
            return
        end
        local healthPercent = health:GetPercent()
        local sanityPercent = sanity:GetPercent()
        local hungerPercent = hunger:GetPercent()
        --创建一个表来持有物品和对应的百分比值
        local percentTable = {
            { item = "tf_rice_ball", value = healthPercent },
            { item = "tf_sandwich",  value = sanityPercent },
            { item = "tf_hamburger", value = hungerPercent }
        }
        --按百分比值对表进行排序，最小的百分比在最前面
        table.sort(percentTable, function(a, b) return a.value < b.value end)

        --获取最小百分比对应的物品
        local lootItem1 = percentTable[1].item
        local lootItem2 = percentTable[2].item
        local lootItem3 = percentTable[3].item

        --根据最小百分比结果设置loottable
        loottable[lootItem1] = 98
        loottable[lootItem2] = 0
        loottable[lootItem3] = 0
        loottable["tf_rainbow_apple"] = 2
    end,

    lootfn = function(inst, doer)
        inst.setupdata.UpdateLootFood(inst.setupdata.loottable, doer)

        local total = 0
        for _, v in pairs(inst.setupdata.loottable) do
            total = total + v
        end
        --print ("TOTOAL:", total)
        --for k,v in pairs(inst.setupdata.loottable) do print(" - ", tostring(v/total), k) end

        local item = weighted_random_choice(inst.setupdata.loottable)

        return { item }
    end,

    master_postinit = function(inst, setupdata)
        inst.build = "tf_box"
        inst.setupdata = setupdata
        inst.wet_prefix = STRINGS.WET_PREFIX.POUCH
        -- inst.components.inventoryitem:InheritMoisture(100, true)
    end,
}

return MakeBundle("tf_box", table.getkeys(tf_box.loottable), false, tf_box)
